/*
 * @lc app=leetcode.cn id=501 lang=javascript
 *
 * [501] 二叉搜索树中的众数
 */

const { func } = require("joi");

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var findMode = function (root) {
   let res=[]
   let map={}
   let max=1
   let help=function(node){
       if(!node){return}
       help(node.left)
       if(map[node.val]){
           map[node.val]++
           max=map[node.val]>max?map[node.val]:max
       }else{
           map[node.val]=1
       }
       help(node.right)
   }
   help(root)
  
   for(let i in map){
      if(map[i]==max){
          res.push(i)
      }
   }
   return res
};
// @lc code=end

var findMode = function(root) {
    let base = 0, count = 0, maxCount = 0;
    let answer = [];

    const update = (x) => {
        if (x === base) {
            ++count;
        } else {
            count = 1;
            base = x;
        }
        if (count === maxCount) {
            answer.push(base);
        }
        if (count > maxCount) {
            maxCount = count;
            answer = [base];
        }
    }

    const dfs = (o) => {
        if (!o) {
            return;
        }
        dfs(o.left);
        update(o.val);
        dfs(o.right);
    }

    dfs(root);
    return answer;
};
